package com.sunday.common.mongo.query;

import com.sunday.common.core.gson.GsonUtils;
import lombok.Data;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Query;

import java.io.Serializable;

/**
 * 查询 Wrapper
 *
 * @author zsy
 * @since 2022/10/29
 */
@Data
@RequiredArgsConstructor
public class QueryData implements Serializable {

    //查询条件
    private @NonNull String queryObject;
    //查询过滤字段
    private @NonNull String fieldsObject;
    //查询排序
    private @NonNull String sortObject;
    //分页条件
    private long skip;
    //分页条件
    private int limit;
    //索引规则
    private String hint;

    /**
     * 构建 Query
     *
     * @return {@link Query}
     */
    public Query query() {
        BasicQuery basicQuery = new BasicQuery(queryObject, fieldsObject);
        basicQuery.setSortObject(Document.parse(sortObject));
        basicQuery.skip(skip).limit(limit);
        if (StringUtils.isNotBlank(hint)) {
            basicQuery.withHint(hint);
        }
        return basicQuery;
    }

    @Override
    public String toString() {
        return GsonUtils.DEFAULT.toJson(this);
    }

}
